package com.jzr.medical.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;


public class HttpUtil {
    public static String post(String url, String json) throws IOException {
        String apiKey = "BT919";
        String token = "AA317A4454337F54F2ABF2BCA7547585";

        String query = "";
        int start = url.indexOf('?');
        if(start != -1){
            query = url.substring(start+1);
            String[] params = query.split("&");
            SortedMap<String,String> sortedMap = new TreeMap<String, String>();
            for(String p : params){
                String[] items = p.split("=");
                if(items.length>=2){
                    sortedMap.put(items[0],items[1]);
                }
            }
            StringBuilder sbQuery = new StringBuilder();
            for(Map.Entry<String,String> entry : sortedMap.entrySet()){
                sbQuery.append(entry.getKey());
                sbQuery.append("=");
                sbQuery.append(entry.getValue());
            }
            query = sbQuery.toString();
        }

        if(json == null || json.trim().length()<=0){  //如果是空值，请传空的Json Object
            json = "{}";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String timestamp = sdf.format(new Date());
        String sign = apiKey + " "+MD5Util.MD5(query +json+token+timestamp); //apiKey和md5值用一个空格隔开

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("sign",sign);
        httpPost.addHeader("timestamp",timestamp);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;

        StringEntity entity = new StringEntity(json,"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        HttpResponse resp = client.execute(httpPost);
        HttpEntity he = resp.getEntity();
        respContent = EntityUtils.toString(he,"UTF-8");

        return respContent;

    }
}
